clear all
global system "linux"
set more off
set matsize 4000

if "${system}" == "linux" {
	*global code "/"
	global code "/"
	global s "/"
}

run "${code}${s}_set-path.do"

args index
cap log close _all
log using "${log}/log-jc-prepaid-`index'", name("log`index'") text replace


local Age = 12 + `index'* 12

local VarAge "pp`Age'"
di "`VarAge'"

*** Load data
use "${temp}/embs-lps-matched.dta", clear  // 12c-embs-lps-match.do




// specifications
do "_embs-lps-spec.do"


** Merge performance variables
qui su termination_date
gen max_age = mofd(`r(max)') - orig_ym + 1
gen last_age = mofd(termination_date) - orig_ym + 1
replace last_age = . if inlist(termination_type_id, "6", "M")==1

gen pp`Age' = 0 if max_age >= `Age'
replace pp`Age' = 1 if pp`Age'==0 & last_age <= `Age'



** Polynomials
gen PaboveC1 = PaboveC
gen PaboveC2 = PaboveC * PaboveC 
gen PaboveC3= PaboveC2* PaboveC


global poly1 "PaboveC 1.HiP#c.PaboveC1"
global poly2 "$poly1 PaboveC2 1.HiP#c.PaboveC2"
global poly3 "$poly2 PaboveC3 1.HiP#c.PaboveC3"



** rate x month FE
gen ratebin = floor(orig_rate/.25)
*gen ratebin = floor(orig_rate/.5)
egen rate_ym = group(ratebin orig_ym)



** Plot
local Poly $poly3
reghdfe `VarAge' HiP `Poly' $controls, a(${FEs} FErate=rate_ym) vce(robust)
estimate save "${Estimates}/embs-lps-`VarAge'", replace


predict resid, r
drop FE* 
foreach x in HiP `Poly' {
	replace resid = resid + _b[`x']* (`x')
}

qui su `VarAge' if HiP==0
replace resid = resid + `r(mean)'

preserve
	replace PaboveC = ceil(PaboveC/2.5)*2.5
	collapse resid, by(PaboveC)
	
	qui do "${code}/_labels"
	
	twoway scatter resid PaboveC, xline(0) xlabel(-150(50)150) ///
	 saving("${Estimates}/embs-lps-`VarAge'.gph", replace) ///
	 title("Loan Age `Age'") ytitle("") xtitle("")  ylabel(, angle(0)) /* aspect(.7) */
restore

cap log close _all
